package com.ithiema.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ithiema.reggie.common.R;
import com.ithiema.reggie.pojo.User;
import com.ithiema.reggie.service.UserService;
import com.ithiema.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

@PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //随机生成四位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
//            session.setAttribute(phone,code);
            //redis获取
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return R.success("手机验证码发送成功");
        }
return R.error("发送失败哦");
    }
//移动端
    @PostMapping("login")
    public R<String> login(@RequestBody Map map, HttpSession session) {
log.info(map.toString());
        log.info("map:{}",map);
//获取手机号
        String phone = map.get("phone").toString();
  //获取验证码
       String code = map.get("code").toString();

        //验证
//        Object codeInSession = session.getAttribute(phone);
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        //判断
        if (codeInSession!=null&&codeInSession.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user==null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);


            }
            session.setAttribute("user",user.getId());
            //删除
            redisTemplate.delete(phone);
            return R.success("登录成功");
        }
        return R.error("失败");
    }
}
